#!/usr/bin/env pytho
# -*- coding: UTF-8 -*-

import json,time
import requests
import threading
import conf_init as config
from flask import Flask,jsonify,request
from face_model_inference import MaskHandler
import base64
import os
import datetime
from werkzeug.utils import secure_filename
from gevent import pywsgi

app=Flask(__name__)

with open("credits.json", encoding="utf-8") as f:
    g_credits = json.load(f)

handler=MaskHandler()

appkeylist = ["plat", "evabot", "firebot"]
tokenlist = ["plat", "evabot", "firebot"]

try:
   isSuccess=handler.start(False)
   if(not isSuccess):
      print("烟雾识别模型识别服务启动失败")
   print("烟雾识别模型识别服务已正常启动,监听端口:"+str(config.fire_server_port))
except Exception as e:
    print("exception:",e)

@app.route("/face_temperature/upload_file",methods=['POST'])
def inference_detector_netfile():
    model_type=1
    return inference_detector_netfile_internal(model_type)
    
@app.route("/face_temperature_1/upload_file",methods=['POST'])
def inference_detector_netfile_drone():
    model_type=1
    return inference_detector_netfile_internal(model_type)

@app.route("/smoke/json",methods=['POST','GET'])
def inference_detector_netimg():
    model_type=1
    return inference_detetcor_netimg_internal(model_type)
@app.route("/smoke_1/json",methods=['POST','GET'])
def inference_detector_netimg_drone():
    model_type=1
    return inference_detetcor_netimg_internal(model_type)

def inference_detector_netfile_internal(model_type=1):
     
    username = request.form.get("username")
    password = request.form.get("password")
    print('username=' + username)
    #print('password=' + password)
    if username is None or username =='' or username  not in g_credits or password is None or password == '':
        msg ="Username or password is not right, please check! "
        result={"statusCode":-8,"message":msg}
        result["data"]=[]
        print(msg)
        return jsonify(result)
    password = base64.b64decode(password).decode("utf8")
    if g_credits[username] != password:
        msg = username+"'s password is not right, please check! "
        result={"statusCode":-9,"message":msg}
        result["data"]=[]
        print(msg)
        return jsonify(result)
    print("username",username)    
    file = request.files.get("image")
    if file is None or file =='':
        msg ="Can't acquire the upload file,please check if you have attached it into the post form!"
        result={"statusCode":-10,"message":msg}
        result["data"]=[]
        print(msg)
        return jsonify(result)
    filename = file.filename
    #filename = secure_filename(filename)
    print("The file uploaded is ",filename)

    #file_content = file.read()
    #img_data = file_content.decode("utf-8")
    img_data = file.read()
    visual_result = request.form.get("visual_result")
    #print("form.visual_result",visual_result)
    if visual_result is None or visual_result=='':
        visual_result= False
    else:
        visual_result = True if (visual_result == 'True' or visual_result == True) else False
    #print("final visual_result",visual_result)
    
    jsonData, b64_img, global_max_temp = handler.runDetectorNetFile(model_type,img_data,visual_result)
    result={"statusCode":0,"message":u"success", "global_max_temp" : global_max_temp}
    result["data"] = jsonData
    if b64_img is not None:
       result["base64"]=b64_img
    #print(result)
    res = jsonify(result)
    #print("res",res)
    return res
    #return jsonify(result)
    



def inference_detetcor_netimg_internal(model_type=1):    
    
    if request.headers.get("Content-Type")!='application/json':
       return jsonify({"statusCode":-11,"message":"Failed! The request Content-Type value is not right, it should be application/json !"}) 
    data = json.loads(request.data)
    username = data["username"]
    password = data["password"]
    if username is None or username =='' or username  not in g_credits or password is None or password == '':
        msg ="Username or password is not right, please check! "
        result={"statusCode":-12,"message":msg}
        result["data"]=[]
        print(msg)
        return jsonify(result)
    password = base64.b64decode(password).decode("utf8")
    print("username",username)
    print("password",password)
    if g_credits[username] != password:
        msg = username+"'s password is not right, please check! "
        result={"statusCode":-13,"message":msg}
        result["data"]=[]
        print(msg)
        return jsonify(result)
       

    if 'image' in data:
       img_base64 = data['image']
    else:
       msg ="Can't acquire the image value,please check if you have put image data in the request json-data!"
       result={"statusCode":-15,"message":msg}
       result["data"]=[]
       print(msg)
       return jsonify(result)
    #print("request data: image=",img_base64)
    if 'visual_result' in data:
       visual_result = data['visual_result']
    else:
       visual_result = None
    print("request data: visual_result=",visual_result)
    if visual_result is None or visual_result=='':
       visual_result = False
    else:
       visual_result = True if (visual_result == 'True' or visual_result == True) else False
    print("final visual_result",visual_result) 
    #print("request data: image=",img_base64)
    
    jsonData, b64_img, global_max_temp = handler.runDetectorNetImg(model_type,img_base64,visual_result)
    result={"statusCode":0,"message":u"success", "global_max_temp" : global_max_temp}
    result["data"] = jsonData
    if b64_img is not None:
       result["base64"]=b64_img
    return jsonify(result)

if __name__ == "__main__":
    #app.run(host="0.0.0.0",port=config.defects_server_port)
    server = pywsgi.WSGIServer(('0.0.0.0', config.fire_server_port), app)
    server.serve_forever()

